<?php
class Node {
    private $db         = false;
    private $id         = 0;
    private $name       = '';
    private $content    = '';
    private $url        = '';
    
    function __construct() {
        global $db;
        $this->db = $db;
    }
    
    public function save() {
        if ( !$this->id ) {
            $query = 'INSERT INTO node (name,content,url) VALUES ('.$this->db->quote($this->name).','.$this->db->quote($this->content).','.$this->url.')';
            if ($this->db->query($query)) {
                $this->id = mysql_insert_id();
            }
        }
    }
    
    public function loadData() {
        if (!$this->id) {
            return;
        }
        $query = 'SELECT * FROM node WHERE id = '.$this->db->quote($this->id).' LIMIT 1;';
        $data  = $this->db->query($query);
        if (is_array($data) && count($data)) {
            $data           = array_pop($data);
            $this->name     = $data['name'];
            $this->content  = $data['content'];
            $this->url      = $data['url'];
        } else {
            $this->id       = false;
        }
    }
    
	public function addLink($linkTypeId, $toId) {
		$query = 'SELECT 1 FROM link WHERE `from` = '.$this->id.' AND `to` = '.$toId.' AND relation = '.$linkTypeId.' LIMIT 1;';
		$result = $this->db->query($query);
		if (is_array($result) && count($result)) {
			$query = 'UPDATE link SET value = value + '.LINK_VALUE.' WHERE `from` = '.$this->id.' AND `to` = '.$toId.' AND relation = '.$linkTypeId;
	    } else {
			$query = 'INSERT INTO link (value,`from`,`to`,relation) VALUES ('.LINK_VALUE.', '.$this->id.', '.$toId.', '.$linkTypeId.')';
		}
		return $this->db->query($query);
	}

	public function renderLink($attributes = array()) {
        echo ' <a class="'.$attributes['class'].'" href="'.$this->getNodeLocalUrl().'">'.$this->name.'</a> ';
    }	

    function setId($id) {
        $this->id = (int)$id;
    }
    
    public function setName( $name ) {
        $this->name = htmlescape( trim( $name ) );
    }
    
    public function setContent( $content ) {
        $this->content = htmlescape( trim( $content ) );
    }
    
    public function setSystype( $systype ) {
        $this->systype = (int)$systype;
    }

    public function setUrl( $url ) {
        $this->url = $url;
    }

    public function getId() {
        return $this->id;
    }
    
    public function getName() {
        return $this->name;
    }
    
    public function getContent() {
        return $this->content;
    }

    public function getNodeLocalUrl() {
        return DOMAIN.'/'.urlescape($this->name).'/node/'.$this->id;
    }
        
    public function getUrl() {
        return $this->url;
    }
    
    public function renderUrl() {
        if ( $this->url ) {
            echo 'URL: <a href="'.$this->url.'">'.$this->url.'</a>';
        }
    }
}